#!/bin/bash
# 多实例安装
BASE_DIR=/mysql
DATA_DIR=/data
ports='3306 3307 3308 3309 3310'
online=0

function create_user() {
  # create group and user
  groupadd mysql
  useradd  -r -g mysql mysql
}

function tarxz_install(){
  ### 这里需要放下载地址，最好下载下来，用包的形式安装；批量ansible安装
  if [ $online ];then
    URL_Download=https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.20-linux-glibc2.12-x86_64.tar.xz
    yum install -y wget
    fileName=${URL_Download##*/}
    wget ${URL_Download} -O ${BASE_DIR}/${fileName} || echo -e "\033[31m install mysql failed \033[0m"
  else
    fileName=mysql-8.0.20-linux-glibc2.12-x86_64.tar.xz
    cp ${fileName}  ${BASE_DIR}/
  fi
  tarFile=${fileName%.*}
  [ -d ${BASE_DIR}/etc ] && rm -rf ${BASE_DIR}/etc/* ||   mkdir -p ${BASE_DIR}/etc
  [ -d ${DATA_DIR} ] && rm -rf ${DATA_DIR}/* || mkdir -p ${DATA_DIR}

  cd ${BASE_DIR} && xz -d ${fileName} && cd -
  tar -xvf ${BASE_DIR}/${tarFile} -C ${BASE_DIR}/
  mv ${BASE_DIR}/${tarFile%.*} ${BASE_DIR}/${tarFile%%.*}
  mkdir ${BASE_DIR}/${tarFile%%.*}/etc
  mv mysql.cnf ${BASE_DIR}/${tarFile%%.*}/etc/ || (echo -e "\033[31m install mysql failed, not found cnf \033[0m" exit 1)
  cd ${BASE_DIR}/${tarFile%%.*}
  id mysql || create_user #(echo -e "\033[31m please create mysql user \033[0m" && exit 1)
  for port in ${ports}
  do
    cp ${BASE_DIR}/${tarFile%%.*}/etc/mysql.cnf my.cnf
    sed -i "s/3306/${port}/g" my.cnf
    mv -f my.cnf ${BASE_DIR}/${tarFile%%.*}/etc/my${port}.cnf
    # root操作的文件修改权限
    chown -R mysql:mysql ${BASE_DIR}/${tarFile%%.*}
    ./bin/mysqld --defaults-file=${BASE_DIR}/${tarFile%%.*}/etc/my${port}.cnf --basedir=${BASE_DIR} --datadir=${DATA_DIR}/mysql_${port} --initialize-insecure
    [ $? -ne 0 ] && echo -e "\033[31m install mysql${port} failed \033[0m"
    echo -e "\033[32m install mysql${port} successful \033[0m"
    echo -e "\033[32m for convenience please create alias to /root/.bashrc\033[0m"
    cat /root/.bashrc | grep mysql${port} || echo "alias mysql${port}=\"${BASE_DIR}/${tarFile%%.*}/bin/mysql -S ${DATA_DIR}/mysql_${port}/mysql.sock\"" >> /root/.bashrc
    source /root/.bashrc
    # start mysql
    ./bin/mysqld_safe --defaults-file=${BASE_DIR}/${tarFile%%.*}/etc/my${port}.cnf --user=mysql &
  done
  # mysql
  #mysql${port}
  #create user 'admin'@'%' identified by 'admin';
  #grant all privileges on *.* to admin@'%' with grant option;
}

tarxz_install